<template>
  <!-- 注册成公共组件 -->
  <div class="swiper-container" ref="container">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="img in imageList" :key="img.id">
        <img :src="img.imgUrl" :alt="img.imgName" />
      </div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>

    <!-- 如果需要导航按钮 -->
    <!--  -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </div>
</template>

<script>
import Swiper from "swiper";

import "swiper/css/swiper.min.css";
export default {
  name: "Carousel",
  props: {
    imageList: Array,
  },
  watch: {
    // 一旦imageList有值，就触发监视属性
    imageList: {
      handler(val) {
        // 为了第一个轮播图第一次不要new Swiper
        if (val.length === 0) return;
        // 等DOM元素更新完成
        this.$nextTick(() => {
          // 找到所有swiper容器变成轮播图
          const mySwiper = new Swiper(this.$refs.container, {
            // 自动轮播
            autoplay: true,
            // autoplay: {
            //   delay: 1000,
            // },
            // 无缝轮播
            loop: true,
            // 小圆点
            pagination: {
              el: ".swiper-pagination",
            },
            // 左右箭头
            navigation: {
              nextEl: ".swiper-button-next",
              prevEl: ".swiper-button-prev",
            },
          });
          // console.log(mySwiper);

          // 6.6.2之前的版本需要通过代码实现此功能
          // 鼠标移入轮播停止，鼠标移出轮播开始
          mySwiper.el.onmouseenter = function() {
            mySwiper.autoplay.stop();
          };
          mySwiper.el.onmouseleave = function() {
            mySwiper.autoplay.start();
          };

          this.mySwiper = mySwiper;
        });
      },
      // 一上来就触发
      immediate: true,
    },
  },
  beforeDestroy() {
    this.mySwiper.el.onmouseenter = null;
    this.mySwiper.el.onmouseleave = null;
  },
  mounted() {
    // new Swiper(".swiper-container", {
    //   // 自动轮播
    //   autoplay: true,
    //   // autoplay: {
    //   //   delay: 1000,
    //   // },
    //   // 无缝轮播
    //   loop: true,
    //   // 小圆点
    //   pagination: {
    //     el: ".swiper-pagination",
    //   },
    //   // 左右箭头
    //   navigation: {
    //     nextEl: ".swiper-button-next",
    //     prevEl: ".swiper-button-prev",
    //   },
    // });
  },
};
</script>

<style  scoped>
</style>